from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.urls import reverse
from django.db.models import Q
import json
from .models import User, Product, Category
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from alipay.aop.api.response.AlipayTradePagePayResponse import AlipayTradePagePayResponse
import logging
import traceback
import time

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a',
)
logger = logging.getLogger('') 

# 隐私政策视图
def privacy_policy(request):
    """显示隐私保护协议页面"""
    return render(request, 'privacy_policy.html')


def user_agreement(request):
    """显示用户协议页面"""
    return render(request, 'user_agreement.html')

# 搜索视图
def search(request):
    """处理搜索请求"""
    query = request.GET.get('query', '')
    if query:
        # 在商品标题、描述和类别中搜索
        products = Product.objects.filter(
            Q(title__icontains=query) |
            Q(description__icontains=query) |
            Q(category__name__icontains=query),
            is_displayed=True
        ).distinct()
    else:
        products = Product.objects.all()
    
    return render(request, 'search_results.html', {
        'query': query,
        'products': products,
        'user_id': request.session.get('user_id'),
        'user_phone': request.session.get('user_phone'),
        'user_nickname': request.session.get('user_nickname')
    })

# 商品详情视图
def product_detail(request, product_id):
    """显示商品详情页面"""
    product = get_object_or_404(Product, id=product_id)
    categories = Category.objects.all()
    
    # Pass session information to template
    return render(request, 'product_detail.html', {
        'product': product,
        'categories': categories,
        'user_id': request.session.get('user_id'),
        'user_phone': request.session.get('user_phone'),
        'user_nickname': request.session.get('user_nickname')
    })

# 支付宝支付视图
def alipay_pay(request, price):
    """处理支付宝支付请求"""
    user_id = request.session.get('user_id')
    if not user_id:
        messages.error(request, '请先登录')
        return redirect('login')
    
    try:
        user = User.objects.get(id=user_id)
        # 初始化支付宝客户端配置
        alipay_client_config = AlipayClientConfig()
        alipay_client_config.server_url = "https://openapi.alipay.com/gateway.do"
        alipay_client_config.app_id = "2021005166660365"
        alipay_client_config.app_private_key = "MIIEpAIBAAKCAQEAnhOejEiuh1ftIerzNq1MhAjRE/V5mFA00fbwzqj6p9RbqFcBxrOov4f2hFBFmPXJO6Rqqt5lzhwvjSIvxU11/fZfcuKg6j3sBMAABgKR+iRiht7z4F5jvQ+XBZd0B5V5OUw0OE8tc/79Tg+iwU0aLZQFagD9zn7/Xux5q0jYgCKQPDlYUYDnxOYdzIkCDzvQWi35p2w1tJMxrWEW7qTmBBfdtLjHxJQtm7cerhRFUpOwrNdMEQhOWXnRQ5CI8QzOrMkFR7GwmVg5tIhGSloYo64hdG1yqTJ6HY1i2UeyNtn8lrceafLFXLD2IZy1Buu/drhezJcoanR9pRpUipNyXwIDAQABAoIBAGsgBpkxBD2qQ4Rx0aLjLHBp/S6Wc3HaIQGNZMHYWA12Zysc05JR3HD39gLS12eCYX4uvS7QipN0HHF7kn4WMXkLBsI3fS9hCVpqt1lbUov/LloSK5mIvfS45PKgIbyl+kHvN5BVcAsk6YqGJBj1ZGEw575fr6DKBcvRW97M/hNOx14gwTZgseDcyX+dg3NPUYXurLA2aT3VJRoSMk1U/+fesAdAjKrwF9MH+y4nXd0RZvg6wqPKKcXS7ESSKjJogbBD4Ii5zLscqznbtl5SmU+8BqVFGAArBZ+OcXyBXoNdOhJU9eLbYAKjuGqblvPsYgpUOYUIlWDVQYkKXQIM36kCgYEA20+NLGUkmKEWSOEM1j0SXKQtsYKAW8PeGVppbzkcKhuHSl+6N9rB5mh26Smml/gscWhIolISxohL8pwIcxsdYR0VgVg+rgjIGK8xr71H7TUU27IiCYfPtRa7J7yX3PeM7YZa4MKTiUyj9ZNj10cHxRmvQe04qoAxciFSL5UcrdMCgYEAuIWWSgc+qbsOsszKj/AwNtdAv9voOpdGh2KWGglb/2Ug+lA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B"
        
        # 创建支付宝客户端
        client = DefaultAlipayClient(alipay_client_config, logger)
        
        # 创建交易模型
        model = AlipayTradePagePayModel()
        model.out_trade_no = f"{user.id}-{int(time.time())}"
        model.subject = "充值服务"
        model.total_amount = price
        model.product_code = "FAST_INSTANT_TRADE_PAY"
        
        # 设置PC扫码支付的方式
        # model.qr_pay_mode = "1"
        
        # 设置商户自定义二维码宽度
        # model.qrcode_width = 100
        
        request = AlipayTradePagePayRequest(biz_model=model)
        
        # 执行请求
        response_content = client.page_execute(request, http_method="GET")

        
        if not response_content:
            logger.error("Failed to execute Alipay request")
            return JsonResponse({
                'status': 'error',
                'message': '支付请求失败'
            })
        
        return redirect(response_content)
        
    except Exception as e:
        logger.error(f"Alipay payment error: {traceback.format_exc()}")
        return JsonResponse({
            'status': 'error',
            'message': "支付处理过程中发生错误"
        })

# 支付成功回调
@csrf_exempt
def alipay_notify(request):
    """支付宝异步通知处理"""
    if request.method == 'POST':
        # 初始化支付宝客户端
        alipay = AlipayClient(
            appid="2024052200222622",
            app_private_key_string="123",
            alipay_public_key_string="123",
            sign_type='RSA2',
            debug=False
        )
        
        # 验证签名
        params = request.POST.dict()
        sign = params.pop('sign', None)
        
        if alipay.verify(params, sign):
            # 支付成功处理逻辑
            trade_status = params.get('trade_status', '')
            if trade_status == 'TRADE_SUCCESS':
                # 更新订单状态
                out_trade_no = params.get('out_trade_no', '')
                # 这里可以添加订单处理逻辑
                
                return JsonResponse({'status': 'success'})
            
        return JsonResponse({'status': 'error'})
    return JsonResponse({'status': 'error'})

# 支付成功返回
def alipay_return(request):
    """支付宝同步通知处理"""
    # 这里可以添加支付成功后的页面跳转逻辑
    messages.success(request, '支付成功！')
    return redirect('home_view')

# 注册视图
def register(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        nickname = request.POST.get('nickname')
        id_card = request.POST.get('id_card')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        agree_privacy = request.POST.get('agree_privacy')

        # 验证是否同意隐私政策
        if not agree_privacy:
            messages.error(request, '必须同意隐私保护协议才能注册')
            return redirect('register')

        # 验证密码是否匹配
        if password1 != password2:
            messages.error(request, '两次输入的密码不一致')
            return redirect('register')

        # 验证手机号是否已注册
        if User.objects.filter(phone=phone).exists():
            messages.error(request, '该手机号已被注册')
            return redirect('register')

        # 创建用户
        user = User.objects.create_user(
            phone=phone,
            nickname=nickname,
            id_card=id_card,
            password=password1
        )

        # 自动登录
        request.session['user_id'] = user.id
        request.session['user_phone'] = user.phone
        request.session['user_nickname'] = user.nickname
        
        return redirect('home_view')
    return render(request, 'registration/register.html')

# 登录视图
def user_login(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        remember = request.POST.get('remember')

        try:
            user = User.objects.get(phone=phone)
            if user.check_password(password):
                if user.is_active:
                    # Store user information in session first
                    request.session['user_id'] = user.id
                    request.session['user_phone'] = user.phone
                    request.session['user_nickname'] = user.nickname
                    
                    if remember:
                        request.session.set_expiry(1209600)  # 14天
                    else:
                        request.session.set_expiry(0)  # 浏览器关闭时过期
                        
                    # Set the authentication backend and login
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)
                    return redirect('home_view')
                else:
                    messages.error(request, '账号已被禁用')
            else:
                messages.error(request, '密码错误')
        except User.DoesNotExist:
            messages.error(request, '用户不存在')

        return redirect('login')

    return render(request, 'registration/login.html')

# 登出视图
def user_logout(request):
    logout(request)
    return redirect('home_view')

# 主页视图
def home_view(request):
    products = Product.objects.all()
    categories = Category.objects.all()[:4]  # Get the first 2 categories
    
    # Ensure session variables are properly set
    user_id = request.session.get('user_id')
    user_phone = request.session.get('user_phone')
    user_nickname = request.session.get('user_nickname')
    
    return render(request, 'home.html', {
        'products': products,
        'categories': categories,
        'user_id': user_id,
        'user_phone': user_phone,
        'user_nickname': user_nickname
    })

# 添加商品视图
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Product, Category
from .forms import ProductForm


def add_product(request):

    # Check if user is logged in via session
    user_id = request.session.get('user_id')
    if not user_id:
        # messages.error(request, '请先登录')
        return redirect('login')

    user = User.objects.get(id=user_id)
    user_product_count = Product.objects.filter(publisher=user).count()

    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save(commit=False)
            # Get user from session
            user = User.objects.get(id=user_id)
            # 扣除1元费用
            if user.account < 1:
                messages.error(request, '余额不足，请充值', extra_tags='alert alert-danger')
                return redirect('add_product')
            
            user.account -= 1
            user.save()
            
            product.publisher = user
            product.save()
            messages.success(request, '信息添加成功！')
            return redirect('product_list')
    else:
        form = ProductForm()
    
    return render(request, 'add_product.html', {
        'form': form,
        'user_nickname': user.nickname if user.nickname else '未知用户',
        'user_phone': user.phone,
        'user_product_count': user_product_count,
        'user_balance': user.account
    })

# 商品列表视图
def product_list(request):
    # 获取分类参数
    category_id = request.GET.get('category')
    category = None
    
    # 获取商品列表
    products = Product.objects.filter(is_displayed=True)
    if category_id:
        category = get_object_or_404(Category, id=category_id)
        products = products.filter(category=category)
    # 获取所有分类
    categories = Category.objects.all()
    
    # 获取查询参数中的分类ID
    category_id = request.GET.get('category')
    
    # 根据分类筛选产品
    if category_id:
        try:
            category = Category.objects.get(id=category_id)
            products = Product.objects.filter(category=category)
        except Category.DoesNotExist:
            products = Product.objects.none()
    else:
        products = Product.objects.all()
    
    # 获取查询参数中的搜索关键词
    search_query = request.GET.get('q')
    if search_query:
        products = products.filter(
            models.Q(title__icontains=search_query) |
            models.Q(description__icontains=search_query)
        )
    
    # Pass session information to template
    return render(request, 'product_list.html', {
        'products': products,
        'categories': categories,
        'category': category if category_id else None,
        'search_query': search_query or '',
        'user_id': request.session.get('user_id'),
        'user_phone': request.session.get('user_phone'),
        'user_nickname': request.session.get('user_nickname')
    })
